package com.qf.filter;

import com.qf.pojo.User;
import com.qf.utils.SYS;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by Administrator on 2021/10/27.
 */
//只拦截cart请求：意味着跟购物车相关的请求必须过来验证登录状态
@WebFilter("/cart")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //判断用户登录状态 session.getAttribute("user")
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();

        String xhr = request.getHeader("xhr");
        //取出记录的用户信息
        Object obj = session.getAttribute(SYS.USER);//session.setAttribute(SYS.USER,"HELLO");
        if (obj != null && obj instanceof User) {
            // 放行
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            //跳转到登录页面????区分同步请求OR异步请求
            if(xhr==null) {
                response.sendRedirect("login.jsp");
            }else {
                PrintWriter writer = response.getWriter();
                writer.write("{\"code\":-1,\"msg\":\"login.jsp\"}");//{"code":-1,"msg":"login.jsp"}
                writer.flush();
                writer.close();
            }
        }


    }

    @Override
    public void destroy() {

    }
}
